﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using MVP;
using Common;
using System.Globalization;

namespace WinForms.Bku
{
    public partial class BukuKasUmum : UserControl, IBukuKasUmumView
    {
        private BukuKasUmumPresenter _presenter;
        public BukuKasUmumPresenter GetPresenter()
        {
            return _presenter;
        }

        public BukuKasUmum()
        {
            _presenter = new BukuKasUmumPresenter(this);
            InitializeComponent();
        }

        public BukuKasUmum(string bulan, string tahun)
            : this()
        {
            Bulan = bulan;
            Tahun = tahun;
        }

        #region IBukuKasUmumView Members

        public DataSet LppbopDataSet
        {
            set
            {
                BindingSource bindingSource = new BindingSource(this.components);
                bindingSource.DataSource = value;
                bindingSource.DataMember = "BukuKasUmum";
                bkuDataGridView.DataSource = bindingSource;
                bkuBindingNavigator.BindingSource = bindingSource;
            }
            get
            {
                return (DataSet)((BindingSource)bkuDataGridView.DataSource).DataSource;
            }
        }

        public void SendMessageInfo(string strMessage)
        {
            MessageBox.Show(strMessage, "Information Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public string Tahun
        { get; set; }

        public string Bulan
        { get; set; }

        public event EventHandler Initialize;
        public event EventHandler Save;

        #endregion

        private void BukuKasUmum_Load(object sender, EventArgs e)
        {
            Initialize(sender, e);
            periodeToolStripLabel.Text = String.Format("BUKU KAS UMUM - {0} {1}", Bulan.ToUpper(), Tahun);
            bkuDataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            bkuDataGridView.ColumnHeadersHeight = bkuDataGridView.ColumnHeadersHeight * 2;
            bkuDataGridView.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
        }

        private void updateToolStripButton_Click(object sender, EventArgs e)
        {

        }

        #region ColumnRowAdded

        private void bkuDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            decimal[] totals = _presenter.HitungJumlah();
            TotalPenerimaan = totals[0];
            TotalPengeluaran = totals[1];
            TotalPajakDisetor = totals[2];
            if (bkuDataGridView.Columns.Contains("kode"))
            {
                for (int i = 0; i < bkuDataGridView.Rows.Count; i++)
                {
                    DataGridViewRow row = bkuDataGridView.Rows[i];
                    int kode = Convert.ToInt32(row.Cells["kode"].Value);
                    if (kode == (int)JenisPajak.PPh21 || kode == (int)JenisPajak.PPh21PPn || kode == (int)JenisPajak.PajakLainnya)
                    {
                        row.DefaultCellStyle.ForeColor = Color.Gray;
                    }
                }
            }
        }

        #endregion ColumnRowAdded

        #region Columns

        private void bkuDataGridView_DataSourceChanged(object sender, EventArgs e)
        {
            bkuDataGridView.AllowUserToAddRows = false;

            bkuDataGridView.Columns["id"].Visible = false;
            bkuDataGridView.Columns["bulan"].Visible = false;
            bkuDataGridView.Columns["tahun"].Visible = false;
            
            bkuDataGridView.Columns["no"].HeaderText = "No.";
            bkuDataGridView.Columns["no"].Width = 50;

            bkuDataGridView.Columns["tanggal"].HeaderText = "Tanggal";
            bkuDataGridView.Columns["tanggal"].DefaultCellStyle.Format = "dd MMMM yyyy";

            bkuDataGridView.Columns["uraian"].HeaderText = "Uraian";
            bkuDataGridView.Columns["uraian"].Width = 350;

            bkuDataGridView.Columns["penerimaan"].HeaderText = "Penerimaan";
            bkuDataGridView.Columns["penerimaan"].Width = 150;
            bkuDataGridView.Columns["penerimaan"].DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("id-ID");
            bkuDataGridView.Columns["penerimaan"].DefaultCellStyle.Format = "c";

            bkuDataGridView.Columns["pengeluaran"].HeaderText = "Pengeluaran";
            bkuDataGridView.Columns["pengeluaran"].Width = 150;
            bkuDataGridView.Columns["pengeluaran"].DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("id-ID");
            bkuDataGridView.Columns["pengeluaran"].DefaultCellStyle.Format = "c";

            bkuDataGridView.Columns["sort_order"].Visible = false;
            bkuDataGridView.Columns["kode"].Visible = false;
            bkuDataGridView.Columns["parent_id"].Visible = false;

            foreach (DataGridViewColumn column in bkuDataGridView.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }

        }

        #endregion Columns

        private void bkuDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if (e.Context == DataGridViewDataErrorContexts.Formatting || e.Context == DataGridViewDataErrorContexts.Display)
            {
                e.ThrowException = false;
            }
            else
                e.ThrowException = true;
        }

        #region CustomHeader

        private void bkuDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            //if (e.RowIndex == -1 && e.ColumnIndex > -1)
            //{
            //    Rectangle r2 = e.CellBounds;
            //    r2.Y += e.CellBounds.Height / 2;
            //    r2.Height = e.CellBounds.Height / 2;

            //    e.PaintBackground(r2, true);

            //    e.PaintContent(r2);
            //    e.Handled = true;
            //}
        }

        private void bkuDataGridView_Paint(object sender, PaintEventArgs e)
        {
            for (int i = -1; i < bkuDataGridView.Columns.Count; i++)
            {
                DrawCustomHeader(i, e);
            }

            if (bkuDataGridView.Rows.Count > 0)
            {
                for (int i = -1; i < bkuDataGridView.Columns.Count; i++)
                {
                    DrawFooter(i, e);
                }
            }
        }

        private void DrawCustomHeader(int columnIndex, PaintEventArgs e)
        {
            if (columnIndex == -1) return;

            int columnNumber = 0;
            switch (bkuDataGridView.Columns[columnIndex].Name)
            {
                case "no":
                    columnNumber = 1;
                    break;
                case "tanggal":
                    columnNumber = 2;
                    break;
                case "uraian":
                    columnNumber = 3;
                    break;
                case "penerimaan":
                    columnNumber = 4;
                    break;
                case "pengeluaran":
                    columnNumber = 5;
                    break;
                case "pajak":
                    columnNumber = 6;
                    break;
                default:
                    columnNumber = -1;
                    break;
            }
            if (columnNumber == -1) return;

            // Header
            Rectangle rec = bkuDataGridView.GetCellDisplayRectangle(columnIndex, -1, true);
            rec.Y += rec.Height / 2;
            rec.Height = rec.Height / 2;
            e.Graphics.DrawLine(new Pen(new SolidBrush(bkuDataGridView.ColumnHeadersDefaultCellStyle.ForeColor)),
                new Point(rec.X, rec.Y), new Point(rec.X + rec.Width, rec.Y));

            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

            e.Graphics.DrawString(columnNumber.ToString(), bkuDataGridView.ColumnHeadersDefaultCellStyle.Font, new SolidBrush(bkuDataGridView.ColumnHeadersDefaultCellStyle.ForeColor), rec, format);
        }

        private void DrawFooter(int columnIndex, PaintEventArgs e)
        {
            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Near;
            format.LineAlignment = StringAlignment.Center;

            Rectangle footer = bkuDataGridView.GetCellDisplayRectangle(columnIndex, bkuDataGridView.Rows.Count - 1, true);
            for (int i = 1; i <= 4; i++)
            {
                footer.Y += footer.Height;
                e.Graphics.FillRectangle(new SolidBrush(bkuDataGridView.ColumnHeadersDefaultCellStyle.BackColor), footer);
                e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.LightGray)), footer);
                if (columnIndex > -1)
                {
                    string columnValue = "";
                    switch (bkuDataGridView.Columns[columnIndex].Name)
                    {
                        case "uraian":
                            switch (i)
                            {
                                case 1:
                                    columnValue = "Jumlah Total";
                                    break;
                                case 2:
                                    columnValue = "Total Pajak Yang Disetor";
                                    break;
                                case 3:
                                    columnValue = "Total Pengeluaran";
                                    break;
                                case 4:
                                    columnValue = "Sisa Dana";
                                    break;
                                default:
                                    columnValue = string.Empty;
                                    break;
                            }
                            break;
                        case "penerimaan":
                            if (i == 2)
                                columnValue = TotalPajakDisetor.ToString("C");
                            break;
                        case "pengeluaran":
                            switch (i)
                            {
                                case 1:
                                    columnValue = TotalPengeluaran.ToString("C");
                                    break;
                                case 2:
                                    columnValue = TotalPajakDisetor.ToString("C");
                                    break;
                                case 3:
                                    columnValue = (TotalPengeluaran - TotalPajakDisetor).ToString("C");
                                    break;
                                case 4:
                                    columnValue = (TotalPenerimaan - (TotalPengeluaran - TotalPajakDisetor)).ToString("C");
                                    break;
                                default:
                                    columnValue = string.Empty;
                                    break;
                            }
                            break;
                        default:
                            break;
                    }
                    e.Graphics.DrawString(columnValue, bkuDataGridView.ColumnHeadersDefaultCellStyle.Font, new SolidBrush(bkuDataGridView.ColumnHeadersDefaultCellStyle.ForeColor), footer, format);
                }
            }
        }

        private void bkuDataGridView_Scroll(object sender, ScrollEventArgs e)
        {
            //Rectangle rtHeader = bkuDataGridView.DisplayRectangle;
            //rtHeader.Height = bkuDataGridView.ColumnHeadersHeight / 2;
            //bkuDataGridView.Invalidate(rtHeader);
        }

        private void bkuDataGridView_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            //Rectangle rtHeader = bkuDataGridView.DisplayRectangle;
            //rtHeader.Height = bkuDataGridView.ColumnHeadersHeight / 2;
            //bkuDataGridView.Invalidate(rtHeader);
        }

        #endregion CustomHeader

        #region ContextMenu
        private void sisipBarisToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BkuEntryForm entry = new BkuEntryForm();
            if (entry.ShowDialog() == DialogResult.OK)
            {
                int selected = Convert.ToInt32(bkuDataGridView.SelectedRows[0].Cells["sort_order"].Value);
                entry.SortOrder = selected;
                _presenter.AddNew(entry.FieldValues);
                bkuDataGridView.Sort(bkuDataGridView.Columns["sort_order"], ListSortDirection.Ascending);
            }
        }

        private void bkuDataGridView_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                var hit = bkuDataGridView.HitTest(e.X, e.Y);
                bkuDataGridView.ClearSelection();
                if (hit.RowIndex < 0)
                {
                    ContextMenuEnabled = false;
                }
                else
                {
                    ContextMenuEnabled = true;
                    bkuDataGridView.Rows[hit.RowIndex].Selected = true;

                    DataGridViewRow row = bkuDataGridView.Rows[hit.RowIndex];
                    int kode = Convert.ToInt32(row.Cells["kode"].Value);
                    if (kode == (int)JenisPajak.PPh21 || kode == (int)JenisPajak.PPh21PPn || kode == (int)JenisPajak.PajakLainnya)
                    {
                        ContextMenuEnabled = false;
                    }
                }
            }
        }

        private void addNewToolStripButton_Click(object sender, EventArgs e)
        {
            BkuEntryForm entry = new BkuEntryForm();
            if (entry.ShowDialog() == DialogResult.OK)
            {
                _presenter.AddNew(entry.FieldValues);
            }
        }

        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BkuEntryForm entry = new BkuEntryForm();
            DataGridViewRow row = bkuDataGridView.SelectedRows[0];
            entry.Id = Convert.ToInt64(row.Cells["id"].Value);
            entry.Bulan = this.Bulan;
            entry.Tahun = this.Tahun;
            entry.KodeRekening = row.Cells["kode"].Value.ToString();
            entry.Nomor = row.Cells["no"].Value.ToString();
            entry.Tanggal = (DateTime)row.Cells["tanggal"].Value;
            entry.Uraian = row.Cells["uraian"].Value.ToString();
            entry.Penerimaan = Convert.ToInt64(row.Cells["penerimaan"].Value);
            entry.Pengeluaran = Convert.ToInt64(row.Cells["pengeluaran"].Value);
            entry.SortOrder = Convert.ToInt32(row.Cells["sort_order"].Value);

            List<DataGridViewRow> childRows = GetChildRows(entry.Id);
            if (childRows.Count > 0)
            {
                DataGridViewRow child = childRows[0];
                entry.Pajak = true;
                entry.JenisPajak = child.Cells["kode"].Value.ToString();
                string columnName = "pengeluaran";
                if (child.Cells[columnName].Value == DBNull.Value)
                    columnName = "penerimaan";
                entry.PajakYangDisetor = Convert.ToDecimal(child.Cells[columnName].Value); ;
            }

            if (entry.ShowDialog() == DialogResult.OK)
            {
                _presenter.Edit(entry.FieldValues);
            }
        }

        private List<DataGridViewRow> GetChildRows(long id)
        {
            List<DataGridViewRow> rows = new List<DataGridViewRow>();
            foreach (DataGridViewRow item in bkuDataGridView.Rows)
            {
                string parentId = item.Cells["parent_id"].Value.ToString();
                if (!string.IsNullOrEmpty(parentId) && Convert.ToInt64(parentId) == id)
                {
                    rows.Add(item);
                }
            }
            return rows;
        }

        private void hapusToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Hapus data?", "Konfirmasi", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                IList<long> ids = new List<long>();
                foreach (DataGridViewRow row in bkuDataGridView.SelectedRows)
                {
                    ids.Add(Convert.ToInt64(row.Cells["id"].Value));
                }
                _presenter.DeleteEntry(ids);
            }
        }

        private void contextMenuStrip_Opening(object sender, CancelEventArgs e)
        {
            e.Cancel = !ContextMenuEnabled;
        }
        #endregion ContextMenu

        private bool ContextMenuEnabled = false;
        private decimal TotalPenerimaan = 0;
        private decimal TotalPengeluaran = 0;
        private decimal TotalPajakDisetor = 0;
    }
}
